package com.application.admin;

import com.application.model.Category;
import com.application.service.CategoryService;
import com.jfinal.ext.kit.MsgException;
import com.jfinal.ext.kit.excel.PoiImporter;
import com.jfinal.ext.kit.excel.Rule;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.base.BaseService;
import com.platform.plugin.ServicePlugin;

import java.io.File;
import java.lang.reflect.Method;
import java.util.*;

@Controller("/admin/import")
public class ImportController extends BaseController {

    Prop prop = PropKit.use("export-config.properties");


    /**
     * 部门资料导入表头格式：类别名称，类别编号,关键词	,描述,	排序
     * 企业基础资料导入：name, address, legalname, legaltel, categoryName, scale, description
     * 行业分类导入格式
     */
    public void index() {
        String type = getPara();
        String clz = type.substring(0, 1).toUpperCase() + type.substring(1);
        String columns = prop.get(type + "_columns");

        long start = System.currentTimeMillis();
        long end;
        Map<String, List<String>> map = new HashMap<>();
        try {
            Class cls = Class.forName("com.application." + type + "." + clz);
            BaseService service = ServicePlugin.getService(type + "Service");

            File file = getFile().getFile();
            List<List<String>> rowList = PoiImporter.readSheet(file, new Rule());

            List<Model> dataList = new ArrayList<>();
            for (int i = 1; i < rowList.size(); i++) {
                List<String> r = rowList.get(i);
                Model obj = (Model) cls.newInstance();
                obj.set("createtime", new Date());

                int j = 0;
                for (String s : columns.split(",|，")) {
                    String val = r.get(j++).trim();
                    obj.put(s.trim(), val);
                }
                dataList.add(obj);
            }

            boolean f = Db.tx(() -> {
                try {
                    Method method = service.getClass().getDeclaredMethod("saveMulti", List.class);
                    List<String> errors = (List<String>) method.invoke(service, dataList);

                    map.put("errors", errors);
                    return errors.size() > 0 ? false : true;
                } catch (Exception e) {
                    e.printStackTrace();
                    List<String> errors = new ArrayList<>();
                    errors.add(e.getCause().getMessage());
                    map.put("errors", errors);
                }
                return false;
            });

            end = System.currentTimeMillis();
            System.out.println("########## cost :" + (end - start) + "ms");
            if (f) {
                renderOk(dataList.size());
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        renderErr(500, "", "导入失败：" + map.get("errors"));

    }




    /**
     * Excel表头格式：类别名称，类别编号,关键词	,描述,	排序
     */
    public void category() {
        File file = getFile().getFile();

        List<Category> dataList = new ArrayList<>();
        List<List<String>> rowList = PoiImporter.readSheet(file, new Rule());
        for (int i = 1; i < rowList.size(); i++) {
            List<String> r = rowList.get(i);
            if(StrKit.isBlank(r.get(0))){//内容已结束,退出
                continue;
            }

            Category c = new Category();
            c.setCreate_time(new Date(System.currentTimeMillis()));
            c.setCategory_no(r.get(0));
            c.setCategory_name(r.get(1));

            if(StrKit.notBlank(r.get(2))){
                Category p = Category.dao.findByNumber(r.get(2));
                if(p != null){
                    c.setParent_id(p.getId());
                } else {
                    throw new MsgException("行号"+ (i+1) +"未找到对应的父类");
                }
            }

            c.setCategory_ord(Integer.valueOf(r.get(3)));
            c.setCategory_status("是".equalsIgnoreCase(r.get(4)) ? 1 : 0);
            dataList.add(c);
        }

        List<String> errors = new ArrayList<>();
        new CategoryService().saveMulti(dataList, errors);

        if (errors.size() > 0) {
//            setAttr("msg", errors.toString());
//            render("/common/msgAjax.html");
            renderErr(400, "", errors.toString());
        } else {
            renderOk(dataList.size());
        }
    }

/*    @Before(Tx.class)
    public void comment(){
        File file = getFile().getFile();

        List<List<String>> rowList = PoiImporter.readSheet(file, new Rule());

        List<ProductComment> comments = new ArrayList<>();
        for (int i = 1; i < rowList.size(); i++) {
            List<String> r = rowList.get(i);
            if(StrKit.isBlank(r.get(0))){//内容已结束,退出
                continue;
            }
            ProductComment comment = new ProductComment();
            Product p = Product.dao.findFirst("select * from t_product where product_no = ? ", r.get(0).trim());
            comment.setCommentUserid(0);
            comment.setOrderId(0);
            comment.setProductId(p.getId());
            comment.setStar(Integer.parseInt(r.get(4)));
            comment.setCommentContent(r.get(5));
            comment.setIsAnon(0);
            comment.setCreateTime(DateUtil.randomDate("2019-07-01", new SimpleDateFormat("yyyy-MM-dd").format(new
                    Date())));
            comment.set("comment_username", r.get(2));
            comment.set("comment_usermobile", r.get(3));
            comments.add(comment);
        }

        Db.batchSave(comments, 50);

        renderOk("refresh", "成功", comments.size());
    }*/
}
